<template>
  <div class="todoapp">
    <TodoHeader @create="createfn" :arr="list" />
    <TodoMain :arr="    showArr" @del="delfn" />
    <TodoFooter :arr="showArr" @change="show" @clear="clearfn" />
  </div>
</template>

<script>
import "../styles/base.css";
import "../styles/index.css";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todolist")) || [],
      getSel: "all"
    };
  },
  name: "",
  methods: {
    createfn(taskname) {
      console.log(taskname);
      // 将数据push进数组里面
      let id =
        this.list.length == 0 ? 100 : this.list[this.list.length - 1].id + 1;
      this.list.push({
        id: id,
        name: taskname,
        isDone: false
      });
    },
    delfn(id) {
      // 1.根据id找索引
      const index = this.list.findIndex(item => item.id == id);
      this.list.splice(index, 1);
    },
    show(str) {
      if (str) {
        this.getSel = str;
      }
    },
    clearfn() {
      this.list = this.list.filter(obj => obj.isDone == false);
    }
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  computed: {
    showArr() {
      if (this.getSel === "yes") {
        return this.list.filter(obj => obj.isDone === true);
      } else if (this.getSel === "no") {
        return this.list.filter(obj => obj.isDone === false);
      } else {
        return this.list;
      }
    }
  },
  watch: {
    list: {
      deep: true,
      handler() {
        // 只要list变化覆盖保存到loaclStorage里
        localStorage.setItem("todolist", JSON.stringify(this.list));
      }
    }
  }
};
</script>

<style scoped>
</style>

